<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\BrandRequest;
use App\Models\Brand;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class BrandsController extends Controller
{
    public function index(Brand $brand)
    {
        $brands = $brand::query()->orderBy('tag','asc')->get();

        return $this->success($brands);
    }

    public function show(Brand $brand)
    {
        return $this->success($brand);
    }

    public function store(Brand $brand, BrandRequest $request)
    {
        $brand->fill($request->all());
        $brand->save();

        return $this->message('添加成功');
    }

    public function update(Brand $brand, BrandRequest $request)
    {
        $brand->update($request->all());

        return $this->message('编辑成功');
    }

    public function destroy(Brand $brand)
    {
        DB::transaction(function () use ($brand) {
            // 删除品牌并删除品牌下所有商品
            $brand->delete();
            $images = DB::table('products')->where('brand_id', $brand->id)->pluck('image');
            $res = Storage::disk('cosv5')->delete($images);
            if ($res) {
                Log::info('图片删除失败，图片地址：' . json_encode($images));
            }
            Product::query()->where('brand_id', $brand->id)->delete();
        });

        return $this->message('删除成功');
    }
}
